package com.anji.sp.push.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.anji.sp.enums.UserStatus;
import com.anji.sp.model.ResponseModel;
import com.anji.sp.push.common.DeviceType;
import com.anji.sp.push.constants.MqConstants;
import com.anji.sp.push.model.po.PushConfiguresPO;
import com.anji.sp.push.model.po.PushMessagePO;
import com.anji.sp.push.model.po.PushUserPO;
import com.anji.sp.push.model.vo.*;

import com.anji.sp.push.service.*;
import com.anji.sp.push.service.impl.PushUtilServiceImpl;
import com.anji.sp.util.StringUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Objects;


/**
 * @Author: Kean
 * @Date: 2021/1/14
 * @Description:
 */
@Component
@Slf4j
public class RabbitmqListener {
    @Autowired
    private PushMessageService pushMessageService;
    @Autowired
    private PushUserService pushUserService;
    @Autowired
    private PushConfiguresService pushConfiguresService;
    @Autowired
    private PushUtilServiceImpl pushUtilService;

    @RabbitListener(
            //绑定队列
            bindings = @QueueBinding(
                    //需要指定queue的名字
                    value = @Queue(
                            //配置队列名称
                            value = MqConstants.directBatchQueue,
                            //是否是持久队列
                            durable = "true"),
                    //配置交换器
                    exchange = @Exchange(
                            //指定交换器名称
                            value = MqConstants.directExchange,
                            //如果声明异常应被忽略
//                            ignoreDeclarationExceptions = "true",
                            //指定具体的交换器类型,有常量类指定
                            type = ExchangeTypes.DIRECT)
                    , key = {MqConstants.routing}
            ))
    public void listenSingle(PushMessageVO pushMessageVO, Message message, Channel channel) throws Exception {
        log.info("接收Single消息：{}", pushMessageVO);
        String json = pushMessageVO.getOperParam();
        JSONObject jsonObject = JSONObject.parseObject(json);
        RequestSendBean requestSendBean = JSON.toJavaObject(jsonObject, RequestSendBean.class);

        if (Objects.isNull(requestSendBean.getDeviceIds())){
            requestSendBean.setDeviceIds(new ArrayList<>());
        }
        ResponseModel responseModel = pushMessageService.queryByMsgId(pushMessageVO);
        PushMessagePO pushMessagePO = (PushMessagePO) responseModel.getRepData();
        if (pushMessagePO.getConsumptionState() != 1) {
            //未消费 发送消息
            //根据AppKey查询配置信息
            PushConfiguresPO pushConfiguresPO = queryConfig(requestSendBean);
            //根据deviceIds查询所有的用户信息集合
            ResponseModel responseModel1 = pushUserService.queryByDeviceIds(requestSendBean.getDeviceIds(),requestSendBean.getAppKey());
            //遍历集合格局deviceType分成不同的集合
            ArrayList<PushUserPO> userBeansHW = new ArrayList<>();
            ArrayList<PushUserPO> userBeansXM = new ArrayList<>();
            ArrayList<PushUserPO> userBeansOP = new ArrayList<>();
            ArrayList<PushUserPO> userBeansVO = new ArrayList<>();
            ArrayList<PushUserPO> userBeansOther = new ArrayList<>();
            ArrayList<PushUserPO> userBeansIOS = new ArrayList<>();
            if (responseModel1.isSuccess()) {
                ArrayList<PushUserPO> pushUserPOS = (ArrayList<PushUserPO>) responseModel1.getRepData();
                for (int i = 0; i < pushUserPOS.size(); i++) {
                    PushUserPO pushUserPO = pushUserPOS.get(i);
                    if (pushUserPO.getDeviceType().equals(DeviceType.HW) && !StringUtils.isEmpty(pushUserPO.getManuToken())) {
                        userBeansHW.add(pushUserPO);
                    } else if (pushUserPO.getDeviceType().equals(DeviceType.XM) && !StringUtils.isEmpty(pushUserPO.getManuToken())) {
                        userBeansXM.add(pushUserPO);
                    } else if (pushUserPO.getDeviceType().equals(DeviceType.OP) && !StringUtils.isEmpty(pushUserPO.getManuToken())) {
                        userBeansOP.add(pushUserPO);
                    } else if (pushUserPO.getDeviceType().equals(DeviceType.VO) && !StringUtils.isEmpty(pushUserPO.getManuToken())) {
                        userBeansVO.add(pushUserPO);
                    } else if (pushUserPO.getDeviceType().equals(DeviceType.IOS)) {
                        userBeansIOS.add(pushUserPO);
                    } else {
                        userBeansOther.add(pushUserPO);
                    }
                }

                //校验是否允许厂商通道
                if (Objects.nonNull(pushConfiguresPO)&& pushConfiguresPO.getChannelEnable().equals(UserStatus.OK.getIntegerCode())){
                    //如果Android允许厂商通道发送消息

                }else {
                    //不允许厂商通道只走极光
                    userBeansOther.addAll(userBeansHW);
                    userBeansOther.addAll(userBeansXM);
                    userBeansOther.addAll(userBeansOP);
                    userBeansOther.addAll(userBeansVO);
                    //四大厂商数据设置为空集合
                    userBeansHW=new ArrayList<>();
                    userBeansXM=new ArrayList<>();
                    userBeansOP=new ArrayList<>();
                    userBeansVO=new ArrayList<>();
                }
                //然后调用多推方法
                pushUtilService.pushAllMsg(requestSendBean, userBeansHW, userBeansXM, userBeansOP, userBeansVO, userBeansOther,
                        userBeansIOS, pushConfiguresPO, pushMessageVO.getMsgId());
            }
            //结束
            ResponseModel r = pushMessageService.queryAmountByMsgId(pushMessageVO);
            if (r.isSuccess()) {
                pushMessageVO = (PushMessageVO) r.getRepData();
            }
            pushMessageVO.setTargetNum(Integer.toString(requestSendBean.getDeviceIds().size()));
            pushMessageVO.setConsumptionState(1);
            pushMessageService.updateByMsgId(pushMessageVO);
        }
        log.info("消费Single结束：{}", pushMessageVO);
        //消费者手动ack机制
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    @RabbitListener(
            //绑定队列
            bindings = @QueueBinding(
                    //需要指定queue的名字
                    value = @Queue(
                            //配置队列名称
                            value = MqConstants.directAllQueue,
                            //是否是持久队列
                            durable = "true"),
                    //配置交换器
                    exchange = @Exchange(
                            //指定交换器名称
                            value = MqConstants.directExchange,
                            //如果声明异常应被忽略
                            ignoreDeclarationExceptions = "true",
                            //指定具体的交换器类型,有常量类指定
                            type = ExchangeTypes.DIRECT)
                    , key = {MqConstants.routing}
            ))
    public void listenAll(PushMessageVO pushMessageVO, Message message, Channel channel) throws Exception {
        log.info("接收All消息：{}", pushMessageVO);
        String json = pushMessageVO.getOperParam();
        JSONObject jsonObject = JSONObject.parseObject(json);
        RequestSendBean requestSendBean = JSON.toJavaObject(jsonObject, RequestSendBean.class);
        if (Objects.isNull(requestSendBean.getDeviceIds())){
            requestSendBean.setDeviceIds(new ArrayList<>());
        }
        ResponseModel responseModel = pushMessageService.queryByMsgId(pushMessageVO);
        PushMessagePO pushMessagePO = (PushMessagePO) responseModel.getRepData();
        int targetNum = 0;
        if (pushMessagePO.getConsumptionState() != 1) {
            //未消费 发送消息
            //根据AppKey查询配置信息
            PushConfiguresPO pushConfiguresPO = queryConfig(requestSendBean);
            //分别查询华为 小米 oppo vivo ios 其他手机用户
            ResponseModel responseModelHW = pushUserService.queryByDeviceType(DeviceType.HW,requestSendBean.getAppKey());
            ArrayList<PushUserPO> userBeansHW = (ArrayList<PushUserPO>) responseModelHW.getRepData();
            targetNum= targetNum+userBeansHW.size();
            ResponseModel responseModelXM = pushUserService.queryByDeviceType(DeviceType.XM,requestSendBean.getAppKey());
            ArrayList<PushUserPO> userBeansXM = (ArrayList<PushUserPO>) responseModelXM.getRepData();
            targetNum= targetNum+userBeansXM.size();

            ResponseModel responseModelOP = pushUserService.queryByDeviceType(DeviceType.OP,requestSendBean.getAppKey());
            ArrayList<PushUserPO> userBeansOP = (ArrayList<PushUserPO>) responseModelOP.getRepData();
            targetNum= targetNum+userBeansOP.size();

            ResponseModel responseModelVO = pushUserService.queryByDeviceType(DeviceType.VO,requestSendBean.getAppKey());
            ArrayList<PushUserPO> userBeansVO = (ArrayList<PushUserPO>) responseModelVO.getRepData();
            targetNum= targetNum+userBeansVO.size();

            ResponseModel responseModelIOS = pushUserService.queryByDeviceType(DeviceType.IOS,requestSendBean.getAppKey());
            ArrayList<PushUserPO> userBeansIOS = (ArrayList<PushUserPO>) responseModelIOS.getRepData();
            targetNum= targetNum+userBeansIOS.size();

            ResponseModel responseModelOther = pushUserService.queryOther(requestSendBean.getAppKey());
            ArrayList<PushUserPO> userBeansOther = (ArrayList<PushUserPO>) responseModelOther.getRepData();
            targetNum= targetNum+userBeansOther.size();

            //校验是否允许厂商通道
            if (Objects.nonNull(pushConfiguresPO)&& pushConfiguresPO.getChannelEnable().equals(UserStatus.OK.getIntegerCode())){
                //如果Android允许厂商通道发送消息

            }else {
                //不允许厂商通道只走极光
                userBeansOther.addAll(userBeansHW);
                userBeansOther.addAll(userBeansXM);
                userBeansOther.addAll(userBeansOP);
                userBeansOther.addAll(userBeansVO);
                //四大厂商数据设置为空集合
                userBeansHW=new ArrayList<>();
                userBeansXM=new ArrayList<>();
                userBeansOP=new ArrayList<>();
                userBeansVO=new ArrayList<>();
            }
            pushUtilService.pushAllMsg(requestSendBean, userBeansHW, userBeansXM, userBeansOP, userBeansVO, userBeansOther,
                    userBeansIOS, pushConfiguresPO, pushMessageVO.getMsgId());
            //结束
            //查询结果
            ResponseModel r = pushMessageService.queryAmountByMsgId(pushMessageVO);
            if (r.isSuccess()) {
                pushMessageVO = (PushMessageVO) r.getRepData();
            }
            //更新状态及数量
            pushMessageVO.setTargetNum(Integer.toString(targetNum));
            pushMessageVO.setConsumptionState(1);
            pushMessageService.updateByMsgId(pushMessageVO);
        }
        log.info("消费all结束：{}", pushMessageVO);
        //消费者手动ack机制
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    public PushConfiguresPO queryConfig(RequestSendBean requestSendBean) {
        //根据AppKey查询配置信息
        PushConfiguresVO pushConfiguresVO = new PushConfiguresVO();
        pushConfiguresVO.setAppKey(requestSendBean.getAppKey());
        ResponseModel responseModelConfig = pushConfiguresService.queryByAppKey(pushConfiguresVO);
        if (responseModelConfig.isSuccess()) {
            return (PushConfiguresPO) responseModelConfig.getRepData();
        }
        return null;
    }
}
